package com.quanshu.exchange.ui.gui.message.group;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baselibrary.util.glide.GlideUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.db.GroupDao;
import com.quanshu.exchange.support.entity.GroupEntity;
import com.quanshu.exchange.support.entity.GroupLabelEntity;
import com.quanshu.exchange.support.entity.ImageFileEntity;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.gui.profile.DialogPhotoSelect;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 创建群组
 * Created by xiniu003 on 2017/12/8.
 */

public class CreateGroupActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.create_group_title)
    TextView createGroupTitle;
    @BindView(R.id.comment_group)
    LinearLayout commentGroup;
    @BindView(R.id.group_head_portrait)
    ImageView groupHeadPortrait;
    @BindView(R.id.group_name)
    EditText groupName;
    @BindView(R.id.group_intro)
    TextView groupIntro;
    @BindView(R.id.group_intro_text)
    TextView groupIntroText;
    @BindView(R.id.group_intro_rel)
    RelativeLayout groupIntroRel;
    @BindView(R.id.group_classify)
    TextView groupClassify;
    @BindView(R.id.group_classify_text)
    TextView groupClassifyText;
    @BindView(R.id.group_classify_rel)
    RelativeLayout groupClassifyRel;
//    @BindView(R.id.create_group_switch)
//    ShSwitchView createGroupSwitch;

    private String groupNameStr;//群昵称
    private String groupIntroStr;//群简介
    private GroupLabelEntity groupLabelEntity;//群类型 下标 - string
    //    private int addGroupCheckInt;//是否需要审核
    private String groupAvatar;//群头像

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_group);
        ButterKnife.bind(this);
//        setSwitch();
        initListener();
    }

//    private void setSwitch() {
//        createGroupSwitch.setOnSwitchStateChangeListener(isOn -> {
//            boolean addGroupCheck = createGroupSwitch.isOn();
//            if (addGroupCheck == true) {
//                addGroupCheckInt = 1;
//            } else {
//                addGroupCheckInt = 0;
//            }
//        });
//    }

    private void setCommentTextColor() {
        if (!TextUtils.isEmpty(groupNameStr) &&
                !TextUtils.isEmpty(groupIntroStr) &&
                groupLabelEntity != null) {
        } else {
        }
    }

    private void doComment() {

        if (TextUtils.isEmpty(groupNameStr)) {
            ToastHelper.toast("请输入群名称");
            return;
        }

        if (TextUtils.isEmpty(groupIntroStr)) {
            ToastHelper.toast("请输入群简介");
            return;
        }

        if (groupLabelEntity == null) {
            ToastHelper.toast("请选择群分类");
            return;
        }

        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .createGroup(AppUtils.getSignParams(currentUser.getMemberid(), groupNameStr, groupIntroStr, groupAvatar,
                        String.valueOf(groupLabelEntity.getId())),
                        currentUser.getMemberid(), groupNameStr, groupIntroStr,
                        groupAvatar, groupLabelEntity.getId(), 1)
                .compose(new BaseTransformer<>(this, true, false))
                .subscribe(new BaseObserver<BaseResponse<GroupEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<GroupEntity> response) {
                        GroupEntity entity = response.getInfo();
                        entity.setOwner(currentUser.getMemberid());
                        GroupDao.getInstance().save(entity);
                        ToastHelper.toast("群聊创建成功");
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                    }
                });
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());

        //提交
        RxViewHelper.getInstance().clicks(commentGroup, aVoid -> doComment());

        //群 -头像
        RxViewHelper.getInstance().clicks(groupHeadPortrait, aVoid -> {
            doShowPhotoDialog();
        });

        RxViewHelper.getInstance().afterTextChangeEvents(groupName, textViewAfterTextChangeEvent -> {
            groupNameStr = groupName.getText().toString();
            setCommentTextColor();
        });

        //群 -简介
        RxViewHelper.getInstance().clicks(groupIntroRel, aVoid -> {

            Intent intent = new Intent(CreateGroupActivity.this, GroupIntroActivity.class);
            intent.putExtra("primeval", groupIntroText.getText().toString());
            startActivityForResult(intent, 7);

        });

        //群 -分类
        RxViewHelper.getInstance().clicks(groupClassifyRel, aVoid -> {
            Intent intent = new Intent(CreateGroupActivity.this, GroupLabelActivity.class);
            if (groupLabelEntity != null) {
                intent.putExtra("GroupLabelEntity", groupLabelEntity);
            }
            startActivityForResult(intent, 8);
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            if (requestCode == 7) {
                groupIntroStr = data.getStringExtra("bian");
                if (!TextUtils.isEmpty(groupIntroStr)) {
                    groupIntroText.setText(groupIntroStr);
                    setCommentTextColor();
                }
            } else if (requestCode == 8) {
                groupLabelEntity = (GroupLabelEntity) data.getSerializableExtra("GroupLabelEntity");
                groupClassifyText.setText(groupLabelEntity.getLabel_name());
                setCommentTextColor();

            } else if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                String path = selectList.get(0).getCutPath();
                GlideUtils.setRoundImageView(this, path, R.drawable.default_img, groupHeadPortrait);
                File file = new File(path);
                if (file != null && file.exists()) {
                    upLoadFile(file);
                } else {
                    ToastHelper.toast("上传图片错误");
                }
            }
        }
    }

    private void doShowPhotoDialog() {

        DialogPhotoSelect dialogPhotoSelect = new DialogPhotoSelect(this);
        dialogPhotoSelect.show();
        dialogPhotoSelect.getAlbumSubject().subscribe(o -> {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())
                    .enableCrop(true)
                    .selectionMode(PictureConfig.SINGLE)
                    .withAspectRatio(1, 1)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
            dialogPhotoSelect.cancel();
        });
        dialogPhotoSelect.getTakePhotoSubject().subscribe(o -> {
            PictureSelector.create(this)
                    .openCamera(PictureMimeType.ofImage())
                    .enableCrop(true)
                    .selectionMode(PictureConfig.SINGLE)
                    .withAspectRatio(1, 1)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
            dialogPhotoSelect.cancel();
        });
    }

    private void upLoadFile(File file) {
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part avatar = MultipartBody.Part.createFormData("img", file.getName(), requestFile);
        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .uploadGroupImg(avatar)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<ImageFileEntity>>() {
                    @Override
                    public void onSuccess(BaseResponse<ImageFileEntity> response) {
                        ImageFileEntity data = response.getInfo();
                        groupAvatar = data.getImgurl();
                    }
                });
    }

}
